# build in python3.5.2
# 作者：陈常鸿
# 由于虚拟币交易为24h T+0交易，感觉开盘价和闭盘价没有多大作用，只留下最高价线和最低价线
# 使用tensorflow来做线性回归
import requests
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

K_line=lambda url,token,sec,hour:requests.get(url+token+'?group_sec='+str(sec)+'&range_hour='+str(hour)).json()
result=K_line('https://data.gateio.io/api2/1/candlestick2/','btc_usdt',60,12)['data']
high=[]
low=[]
time=[]
n=0.0
# (时间，开盘，收盘，最高，最低)
for i in result:
    high.append([float(i[3])])
    low.append([float(i[4])])
    time.append(n)
    n += 1.0

iterion_num=1000
learning_rate=0.003


train_x=np.asarray(time)
train_y=np.asarray(high)
samples=train_x.shape[0]

w=tf.Variable(0.09,name='wright')
b=tf.Variable(6100,name='bais')

X=tf.placeholder("float")
Y=tf.placeholder("float")

pre=tf.add(tf.multiply(X,w),b)
cost=tf.reduce_sum(tf.pow(pre-Y,2))/(2*samples)

optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(iterion_num):
        for (x,y) in zip(train_x,train_y):
            sess.run(optimizer,feed_dict={X:x,Y:y})

        if (i+1) % 50==0:
            c=sess.run(cost,feed_dict={X:train_x,Y:train_y})
            print('集数：', '%04d' % (i + 1), '代价函数：', '{:.9f}'.format(c), '权重=', sess.run(w), '偏差=', sess.run(b))
    # 出图
    plt.figure(figsize=(20, 20))
    plt.plot(time, high, color='red', label='high')
    plt.plot(time, low, color='green', label='low')
    plt.plot(train_x, sess.run(w) * train_x + sess.run(b), label='fix line')
    plt.legend()
    plt.show()